﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

using System.Net.Sockets;
using System.Net;
namespace TcpClient
{
    public class Program
    {

        [STAThread]
        static void Main()
        {
            Socket c = null;
            StreamWriter fileLog = null;
            FileStream fileReader = null;

            
            /*            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            
        }
 */
            
   //     private void Send_File(object sender, EventArgs e)
     //   {
            try
            {
                //// Part one Set up connection 

                int port = 2000;
                string host = "127.0.0.1";
                // try to connect

                byte[] buff = new byte[10240];
                string recvStr = "";
                byte[] recvBytes = new byte[10240];
                int bytes = 1;
                int rbytes = 0;
                int status = 0;
                long position = 0;
                long send_size = 0;

                //FileStream fileReader = null;

                string filename = "";
                string initmsg = "";
                string logFile = "send.log";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);
                //new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Console.WriteLine("Connecting...");
                c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                c.Connect(ipe);

                string[] TransferFiles = null;
                string[] filetype = null;

                int file_count;

                while (true)
                {
                    TransferFiles = Directory.GetFiles(".");

                    file_count = 0;

                    while (file_count < TransferFiles.Length)
                    {
                        filename = TransferFiles[file_count];
                        file_count++;
                        filetype = filename.Split('.');

                        if (!(filetype[filetype.Length - 1] == "tif"))
                        {
                            continue;
                        }

                        file_count = 999;
                        status = 0;

                        filename = filetype[filetype.Length - 2].Substring(1) + "." + filetype[filetype.Length - 1];
                        initmsg = "Initial:" + filename.Trim();

                        byte[] buffHead = Encoding.UTF8.GetBytes(initmsg);

                        c.Send(buffHead, buffHead.Length, 0);

                        Console.Write("I");
                        System.Threading.Thread.Sleep(10);

                        while (status < 5)
                        {
                            bytes = c.Receive(recvBytes, recvBytes.Length, 0);
                            recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes);
                            Console.Write(recvStr + ":" + bytes.ToString());

                            if (recvStr.Trim().Equals(initmsg))
                                break;
                            status++;
                            System.Threading.Thread.Sleep(20);
                        }

                        if (status < 5)
                        {
                            send_size = 0;

                            fileLog = new StreamWriter(logFile, true);

                            File.Move(filename, filename + ".Send");
                            fileReader = new FileStream(filename + ".Send", FileMode.Open, FileAccess.Read);
                            if (fileReader.Length > 0)
                                Console.Write("Start " + fileReader.Length.ToString());
                            // send file size
                            buffHead = Encoding.UTF8.GetBytes(fileReader.Length.ToString());
                            fileLog.WriteLine("Send:" + filename + ":" + fileReader.Length.ToString() + ":");

                            c.Send(buffHead, buffHead.Length, 0);

                            while (status < 5)
                            {
                                bytes = c.Receive(recvBytes, recvBytes.Length, 0);
                                recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes);
                                Console.Write(recvStr + " : " + bytes.ToString());

                                if (recvStr.Trim().Equals(fileReader.Length.ToString()))
                                    break;

                                status++;
                                System.Threading.Thread.Sleep(500);
                            }
                            if (status == 5)
                            {
                                buffHead = Encoding.UTF8.GetBytes("Fail:S");

                                c.Send(buffHead, buffHead.Length, 0);
                                fileReader.Close();
                                File.Move(filename+".Send", filename);
                                fileLog.WriteLine("Failed size");
                                break;
                            }

                            position = 0;

                            while (true)
                            {
                                fileReader.Seek(position, SeekOrigin.Begin);
                                rbytes = fileReader.Read(buff, 0, 10240);

                                position += (long)rbytes;

                                if (rbytes < 1)
                                {
                                    buffHead = Encoding.UTF8.GetBytes("FinIsh");

                                    c.Send(buffHead, buffHead.Length, 0);
                                    fileLog.WriteLine("");
                                    fileLog.WriteLine("Finish:" + send_size.ToString() + ":");

                                    fileReader.Close();
                                    fileLog.Close();
                                    break;
                                }

                                c.Send(buff, rbytes, 0);
                                Console.Write(".");
                                System.Threading.Thread.Sleep(20);


                                bytes = c.Receive(recvBytes, recvBytes.Length, 0);
                                recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes);
                                status = Convert.ToInt32(recvStr);
                                fileLog.Write((status % 10240).ToString()+":");
                                send_size += status;

                                if (!(status.Equals(rbytes)))
                                {
                                    fileLog.WriteLine("");
                                    fileLog.WriteLine("Failed: send error");

                                    break;
                                }
                            }

                            fileReader.Close();
                            fileLog.Close();
                        }
                    }
                    Console.WriteLine("Wait for next file");
                    if (file_count == TransferFiles.Length)
                    {
                        System.Threading.Thread.Sleep(1000 * 6 * 1);
                    }
                    else
                        System.Threading.Thread.Sleep(1200);

                }
                c.Close();

            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine("ArgumentNullException: {0}", ex);
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException: {0}", se);
            }
            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();

        }


    }
}